package com.example.mybatisplusdemo.web.controller;

import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.model.domain.Booking;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.service.IBookingService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yrd
 * @since 2025-07-07
 */
@Slf4j
@RestController
@RequestMapping("/api/booking")
@RequiredArgsConstructor
public class BookingController {

    private final IBookingService bookingService;

    /**
     * 创建航班预订
     * 
     * @param bookingRequest 预订请求参数
     * @return JsonResponse<Map<String, Object>> 预订结果
     */
    @PostMapping("/create")
    public JsonResponse<Map<String, Object>> createBooking(@RequestBody Map<String, Object> bookingRequest) {
        try {
            log.info("收到预订请求: {}", bookingRequest);
            
            // 提取请求参数
            Long flightId = Long.valueOf(bookingRequest.get("flightId").toString());
            Long userId = Long.valueOf(bookingRequest.get("userId").toString());
            String supplier = (String) bookingRequest.get("supplier");
            BigDecimal price = new BigDecimal(bookingRequest.get("price").toString());
            String currency = (String) bookingRequest.getOrDefault("currency", "CNY");
            
            // 创建预订记录
            Booking booking = new Booking()
                    .setUserId(userId)
                    .setFlightId(flightId)
                    .setBookingTime(LocalDateTime.now())
                    .setStatus("PENDING")
                    .setPrice(price)
                    .setCurrency(currency)
                    .setSupplier(supplier)
                    .setSupplierReference("REF" + UUID.randomUUID().toString().replace("-", "").substring(0, 12).toUpperCase());
            
            boolean success = bookingService.save(booking);
            
            if (success) {
                Map<String, Object> result = Map.of(
                        "bookingId", booking.getId(),
                        "status", booking.getStatus(),
                        "supplierReference", booking.getSupplierReference(),
                        "bookingTime", booking.getBookingTime()
                );
                
                log.info("预订创建成功: {}", result);
                return JsonResponse.success(result, "预订创建成功");
            } else {
                log.error("预订创建失败");
                return JsonResponse.failure("预订创建失败");
            }
            
        } catch (Exception e) {
            log.error("预订创建异常: ", e);
            return JsonResponse.failure("预订创建失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询预订信息
     * 
     * @param bookingId 预订ID
     * @return JsonResponse<Booking> 预订信息
     */
    @GetMapping("/{bookingId}")
    public JsonResponse<Booking> getBookingById(@PathVariable Long bookingId) {
        try {
            Booking booking = bookingService.getById(bookingId);
            if (booking != null) {
                return JsonResponse.success(booking, "查询成功");
            } else {
                return JsonResponse.failure("预订记录不存在");
            }
        } catch (Exception e) {
            log.error("查询预订信息异常: ", e);
            return JsonResponse.failure("查询失败: " + e.getMessage());
        }
    }
    
    /**
       * 获取用户预订列表
       * 
       * @return JsonResponse<List<Map<String, Object>>> 用户预订列表
       */
      @GetMapping("/user-bookings")
      public JsonResponse<List<Map<String, Object>>> getUserBookings() {
          try {
              // 使用SessionUtils获取当前用户信息
              User currentUser = SessionUtils.getCurrentUserInfo();
              if (currentUser == null) {
                  return JsonResponse.failure("用户未登录");
              }
              
              List<Map<String, Object>> userBookings = bookingService.getUserBookingsWithFlightInfo(currentUser.getId());
              return JsonResponse.success(userBookings, "查询成功");
          } catch (Exception e) {
              log.error("查询用户预订列表异常: ", e);
              return JsonResponse.failure("查询失败: " + e.getMessage());
          }
      }
    
    /**
     * 取消预订
     * 
     * @param bookingId 预订ID
     * @return JsonResponse<String> 取消结果
     */
    @PostMapping("/{bookingId}/cancel")
    public JsonResponse<String> cancelBooking(@PathVariable Long bookingId) {
        try {
            // 查询预订是否存在
            Booking booking = bookingService.getById(bookingId);
            if (booking == null) {
                return JsonResponse.failure("预订不存在");
            }
            
            // 检查预订状态
            if ("CANCELED".equals(booking.getStatus())) {
                return JsonResponse.failure("预订已取消");
            }
            
            // 更新预订状态为已取消
            booking.setStatus("CANCELED");
            boolean success = bookingService.updateById(booking);
            
            if (success) {
                log.info("预订取消成功: bookingId={}", bookingId);
                return JsonResponse.success("预订已取消", "取消成功");
            } else {
                return JsonResponse.failure("取消失败");
            }
        } catch (Exception e) {
            log.error("取消预订异常: ", e);
            return JsonResponse.failure("取消失败: " + e.getMessage());
        }
    }
}
